<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
// import axios from 'axios'
import * as echarts from 'echarts'

const { proxy }  = getCurrentInstance()

// 获取用户头像函数
const getImageUrl = (user) => {
  return new URL(`../assets/images/${user}.png`, import.meta.url).href
}

// const tableData = ref([
//     {
//       name: "Java",
//       todayBuy: 100,
//       monthBuy: 200,
//       totalBuy: 300,
//     },
//     {
//       name: "Python",
//       todayBuy: 100,
//       monthBuy: 200,
//       totalBuy: 300,
//     }
// ])
const tableData = ref([])
const tableLabel = ref({
    name: "课程",
    todayBuy: "今日购买",
    monthBuy: "本月购买",
    totalBuy: "总购买",
})
const countData = ref([])
const chartData = ref([])
const observer = ref(null)

//这个是折线图和柱状图 两个图表共用的公共配置
const xOptions = reactive({
      // 图例文字颜色
      textStyle: {
        color: "#333",
      },
      legend: {},
      grid: {
        left: "20%",
      },
      // 提示框
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category", // 类目轴
        data: [],
        axisLine: {
          lineStyle: {
            color: "#17b3a3",
          },
        },
        axisLabel: {
          interval: 0,
          color: "#333",
        },
      },
      yAxis: [
        {
          type: "value",
          axisLine: {
            lineStyle: {
              color: "#17b3a3",
            },
          },
        },
      ],
      color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
      series: [],
})

// 这是饼图的配置
const pieOptions = reactive({
  tooltip: {
    trigger: "item",
  },
  legend: {},
  color: [
    "#0f78f4",
    "#dd536b",
    "#9462e5",
    "#a6a6a6",
    "#e1bb22",
    "#39c362",
    "#3ed1cf",
  ],
  series: []
})

// axios({
//   url: '/api/home/getTableData',
//   method: 'get'
// }).then(res => {
//   // console.log(res.data)
//   // 要学会制造假数据，把交互的请求的流程，根据接口文档跑通，还要制造出数据
//   // 此时要用到工具 - mock.js 拦截请求，制造随机数据
//   if (res.data.code === 200) {
//     console.log(res.data.data.tableData)
//     tableData.value = res.data.data.tableData
//   }
// })
const getTableData = async () => {
  const data = await proxy.$api.getTableData()
  // console.log(data)
  // 本地是 data.tableData   线上是 data
  tableData.value = data.tableData
}
const getCountData = async () => {
  const data = await proxy.$api.getCountData()
  // console.log(data)
  countData.value = data
}
const getChartData = async () => {
  const { orderData, userData, videoData } = await proxy.$api.getChartData()
  // console.log(orderData, userData, videoData)
  // chartData.value = data

  // 对 第一个图表-折线图 进行 x轴 和 series 赋值
  xOptions.xAxis.data = orderData.date
  xOptions.series = Object.keys(orderData.data[0]).map(val => ({
    name: val,
    data: orderData.data.map(item => item[val]),
    type: 'line'
  }))
  const oneEchart = echarts.init(proxy.$refs['echart'])
  oneEchart.setOption(xOptions)

  // 对 第二个图表-柱状图 进行渲染
  xOptions.xAxis.data = userData.map(item => item.date)
  xOptions.series = [
    {
      name: '新增用户',
      data: userData.map(item => item.new),
      type: 'bar'
    },
    {
      name: '活跃用户',
      data: userData.map(item => item.active),
      type: 'bar'
    }
  ]
  const twoEchart = echarts.init(proxy.$refs['userEchart'])
  twoEchart.setOption(xOptions)

  // 对 第三个图表-饼图 进行渲染
  pieOptions.series = [
    {
      data: videoData,
      type: 'pie'
    }
  ]
  const threeEchart = echarts.init(proxy.$refs['videoEchart'])
  threeEchart.setOption(pieOptions)

  // 监听页面的变化
  // 如果监听的容器大小发生变化，改变了以后，会执行回调函数，图表会自适应容器来变化
  observer.value = new ResizeObserver(() => {
    oneEchart.resize()
    twoEchart.resize()
    threeEchart.resize()
  })
  // 容器存在
  if (proxy.$refs['echart']) {
    observer.value.observe(proxy.$refs['echart'])
  }
}

onMounted(() => {
  getTableData()
  getCountData()
  getChartData()
})
</script>

<template>
  <el-row class="home" :gutter="20">
    <!-- 左侧 -->
    <el-col :span="8" style="margin-top: 20px;">
      <el-card shadow="hover">
        <div class="user">
          <img :src="getImageUrl('user')" class="user">
          <div class="user-info">
            <p>Admin</p>
            <p>超级管理员</p>
          </div>
        </div>

        <div class="login-info">
          <p>上次登录时间：<span>2020-02-02</span></p>
          <p>上次登录地点：<span>深圳</span></p>
        </div>
      </el-card>

      <el-card class="user-table">
        <el-table :data="tableData">
          <el-table-column
            v-for="(val, key) in tableLabel"
            :key="key"
            :prop="key"
            :label="val"
          ></el-table-column>
        </el-table>
      </el-card>
    </el-col>

    <!-- 右侧 -->
    <el-col :span="16" style="margin-top: 20px;">
      <!-- 右上方六个卡片 -->
      <div class="num">
        <el-card
          :body-style="{display: 'flex', padding: 0}"
          v-for="item in countData"
          :key="item.name"
        >
          <component :is="item.icon" class="icons" :style="{background: item.color}"></component>
          <div class="detail">
            <p class="num">￥{{ item.value }}</p>
            <p class="txt">{{ item.name }}</p>
          </div>
        </el-card>
      </div>

      <!-- 右中折线图 -->
      <el-card class="top-echart">
        <div ref="echart" style="height: 280px;"></div>
      </el-card>

      <!-- 右下柱状图和饼图 -->
       <div class="graph">
        <el-card>
          <div ref="userEchart" style="height: 240px;"></div>
        </el-card>
        <el-card>
          <div ref="videoEchart" style="height: 240px;"></div>
        </el-card>
       </div>
    </el-col>
  </el-row>
</template>

<style lang="less" scoped>
.home {
  height: 100%;
  overflow: hidden;
  .user {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid #ccc;
    img {
      margin-right: 40px;
      width: 150px;
      height: 150px;
      border-radius: 50%;
    }
    .user-info {
      p {
        line-height: 40px;
        &:nth-child(1) {
          font-size: 35px;
        }
        &:nth-child(2) {
          color: #999;
        }
      }
    }
  }

  .login-info {
    p {
      font-size: 14px;
      color: #999;
      line-height: 30px;
      span {
        margin-left: 60px;
        color: #666;
      }
    }
  }

  .user-table {
    margin-top: 20px;
  }

  .num {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .el-card{
      margin-bottom: 20px;
      width: 32%;
    }
    .icons {
      width: 80px;
      height: 80px;
      font-size: 30px;
      text-align: center;
      line-height: 80px;
      color: #fff;
    }
    .detail {
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-left: 15px;
      .num {
        margin-bottom: 10px;
        font-size: 30px;
      }
      .txt {
        font-size: 15px;
        text-align: center;
        color: #999;
      }
    }
  }

  .graph {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;

    .el-card {
      width: 48%;
      height: 260px;
    }
  }
}
</style>